package com.bluedot.service;

import com.alibaba.fastjson.JSONObject;
import com.bluedot.pojo.vo.UserVO;
import com.google.common.collect.Maps;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * token 工具类
 */
public class Token {
    private String secret = "b96bb6cccf5df779edd6e141a0bc6d52";
    private long expire = 3600;

    private String header = "token";

    /*
     * 根据身份ID标识，生成Token
     */
    public String getToken (UserVO user){
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000000);

        //Date expireDate = new Date(nowDate.getTime() + expire * 1000);// 1小时过期（生产环境）

        // Date expireDate = new Date(nowDate.getTime() + 10);// 测试

        Map<String,Object> maps = Maps.newHashMap();
        maps.put("user",user);
        //maps.put("sessionKey",session_key);

        return Jwts.builder()
                // header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg","HS256")
                // payload
                .setSubject(JSONObject.toJSONString(maps))
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .setId(UUID.randomUUID().toString())
                // signature
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
    /*
     * 获取 Token 中注册信息
     */
    public Claims getTokenClaim (String token) {

        JwtParser jwtParser = Jwts.parser().setSigningKey(secret);
        Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body;
    }
}
